/**
 * Issue全局Javascript文件.
 */
var Issue = Issue || {};
Issue.suggest=Issue.suggest||{};
Issue.util = Issue.util || {};

$(document).ready(function(){
	/**
	 * 为一个input设置user的Suggest 多个用户,以逗号分隔
	 * @param {jQuery} input 文本框控件(jquery对象)
	 * @param {Function} callback 后台返回数据行时,对此进行的页面回调操作
	 * @param {Object} options 允许用户复写默认参数
	 */
	Issue.suggest.multiUserSuggest = function Issue_suggest_userSuggest(input, callback, options) {
		var defaultOptions = { 
			max: 30, //列表里的条目数 
			minChars: 1, //自动完成激活之前填入的最小字符 
			width: 400, //提示的宽度，溢出隐藏 
			scrollHeight: 300, //提示的高度，溢出显示滚动条 
			matchContains: false, //包含匹配，就是data参数里的数据，是否只要包含文本框里的数据就显示 
			autoFill: false, //自动填充 
			dataType: "json",
			multiple :true,
			multipleSeparator:",",
			delay: 500,
			cacheLength: 0,
			parse: function(data) {
				return $.map(data, function(row) {
					var email=row.email || "";	
					value = {
							name: row.name || "",
							email: row.email || ""
						};
					return {
						data: value,
						value: value,
						result: email
					};
				});
			},
			formatItem: function(row, i, max) { 
				return row.name +","+row.email; 
			}
		};
		options = $.extend({}, defaultOptions, options || {});
		return input.autocomplete(Issue.constants.CONTEXT+"ajax/users/query?multi=true", options)
			.result(function(event, row, formatted) {
				if (callback && callback instanceof Function){
					callback(row);
				}
			});
	};
	/**
	 * 为一个input设置user的Suggest
	 * @param {jQuery} input 文本框控件(jquery对象)
	 * @param {Function} callback 后台返回数据行时,对此进行的页面回调操作
	 * @param {Object} options 允许用户复写默认参数
	 */
	Issue.suggest.userSuggest = function Issue_suggest_userSuggest(input, callback, options) {
		var defaultOptions = { 
			max: 30, //列表里的条目数 
			minChars: 1, //自动完成激活之前填入的最小字符 
			width: 200, //提示的宽度，溢出隐藏 
			scrollHeight: 300, //提示的高度，溢出显示滚动条 
			matchContains: false, //包含匹配，就是data参数里的数据，是否只要包含文本框里的数据就显示 
			autoFill: false, //自动填充 
			dataType: "json",
			delay: 500,
			cacheLength: 0,
			parse: function(data) {
				return $.map(data, function(row) {
					var username = row.chineseName || "";
						value = {
							name: row.name || "",
							email: row.email || "",
							username: username,
							id: row.id
						};
					return {
						data: value,
						value: value,
						result: value.name
					};
				});
			},
			formatItem: function(row, i, max) { 
				return row.name + "," + row.username; 
			}
		};
		options = $.extend({}, defaultOptions, options || {});
		return input.autocomplete(Issue.constants.CONTEXT+"ajax/users/query", options)
			.result(function(event, row, formatted) {
				if (callback && callback instanceof Function){
					callback(row);
				}
			});
	};
	Issue.display = function(msg,autoClose,callback){
		if(!$('#issue_msg_display').length){
			var alertDiv = $('<div id="issue_msg_display"><p></p></div>');
			alertDiv.appendTo("body");
			alertDiv.dialog({
				autoOpen: false,
				resizable : false,
				width: 300,
				minHeight:68,
				dialogClass : 'panel-success',
				open:function(){
					var self=$(this);
					if(autoClose) {
						setTimeout(function(){self.dialog("close")},800);
					}
				}
			});
		}
		$('#issue_msg_display p').html(msg);
		$('#issue_msg_display').dialog('open');
	};
	Issue.warning=function(msg){
		if(!$('#issue_msg_warning').length){
			var alertDiv = $('<div id="issue_msg_warning"></div>');
			alertDiv.appendTo("body");
		}
		var newTr = "<div id=\"iit-warning-error\" class=\"alert alert-error\"><a data-dismiss=\"alert\" class=\"close\">×</a><strong>Waring!</strong> "+msg+".</div>";
		$("#issue_msg_warning").html(newTr);
	};

    Issue.util.formatDateInterval = function (date) {
		var d = (date instanceof Date) ? date : !isNaN(date) ? new Date(parseInt(date)) : new Date(),
			now = new Date(), intervalDays, interval,
			formatDate = Issue.util.formatDate;

		// 获取自然天数差异的函数
		var getIntervalDays = function(before, after) {
			var b = new Date(before.getTime()), a = new Date(after.getTime());
			b.setHours(0);
			b.setMinutes(0);
			b.setSeconds(0);
			b.setMilliseconds(0);
			a.setHours(0);
			a.setMinutes(0);
			a.setSeconds(0);
			a.setMilliseconds(0);
			return (a.getTime() - b.getTime()) / 86400000;
		};
		intervalDays = getIntervalDays(d, now);

		// 同一个自然天
		if (intervalDays === 0) {
			interval = now.getTime() - d.getTime();

			// 小于一秒钟
			if (interval < 1000) {
				return i18n("tag.diffDateTag.ago.second", 1);
			}
			// 小于一分钟
			else if (interval < 60000) {
				return i18n("tag.diffDateTag.ago.second", (interval / 1000) >> 0);
			}
			// 小于一小时
			else if (interval < 3600000) {
				return i18n("tag.diffDateTag.ago.minute", (interval / 60000) >> 0);
			}
			// 否则必然在一个自然天内且大于一小时
			else {
				return i18n("tag.diffDateTag.ago.today", formatDate(d, "longtime-minute"));
			}
		}
		// 前一个自然天
		else if (intervalDays === 1) {
			return i18n("tag.diffDateTag.ago.yesterday", formatDate(d, "longtime-minute"));
		}
		// 超过两个自然天
		else {
			return formatDate(d, "longdatetime-minute");
		}
	};

    Issue.util.formatDate = function Issue_util_formatDate(date, formatType) {
		var d = !isNaN(date) ? new Date(date) : ((date instanceof Date) ? date : new Date());
		var formatCode = arguments.callee.formats[formatType];
		if (!formatCode) {
			formatCode = arguments.callee.formats["default"];
		}
		var format = i18n(formatCode);
		return Issue.util._formatDate(d, format);
	};

    Issue.util.formatDate.formats = {
		"default": "format.date.default",
		"shortdate": "format.date.short-date",
		"longdate": "format.date.long-date",
		"shorttime": "format.date.short-time",
		"longtime": "format.date.long-time",
		"shortdatetime": "format.date.short-datetime",
		"longdatetime": "format.date.long-datetime",
		"longtime-minute": "format.date.long-time-minute",
		"longdatetime-minute": "format.date.long-datetime-minute"
	};

    /**
	 * 第三方日期格式化函数.
	 *
	 * @method Spark.thirdparty._formatDate
	 * @param date {Date} 日期对象
	 * @param format {String} 格式字符串
	 * @return 格式化之后的日期字符串
	 * @private
	 */
	Issue.util._formatDate = function (date, format) {
		var str = format;
		var week = [ i18n("format.date.week.sunday"),
			i18n("format.date.week.monday"),
			i18n("format.date.week.tuesday"),
			i18n("format.date.week.wednesday"),
			i18n("format.date.week.thursday"),
			i18n("format.date.week.friday"),
			i18n("format.date.week.saturday") ];

		str = str.replace(/yyyy|YYYY/, date.getFullYear());
		str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100));

		str = str.replace(/MM/, date.getMonth() >= 9 ? (date.getMonth() + 1).toString() : '0' + (date.getMonth() + 1));
		str = str.replace(/M/g, date.getMonth());

		str = str.replace(/w|W/g, week[date.getDay()]);

		str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
		str = str.replace(/d|D/g, date.getDate());

		str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
		str = str.replace(/h|H/g, date.getHours());
		str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
		str = str.replace(/m/g, date.getMinutes());

		str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
		str = str.replace(/s|S/g, date.getSeconds());

		return str;
	};
});